﻿using ManageReportVer1.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace ManageReportVer1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return RedirectToAction("Login", "Home");
        }

        //public ActionResult Index()
        //{
        //    DBDataContext DBData = new DBDataContext();
        //    DashboardModel viewModel = new DashboardModel();
        //    List<User> tongUser = (from m in DBData.Users
        //                           orderby m.UserId ascending
        //                           select m).ToList();
        //    List<Role> tongRole = (from m in DBData.Roles
        //                           orderby m.RoleId ascending
        //                           select m).ToList();

        //    //membershipService.GetAllUsers(0, 20, out totalRecords);
        //    viewModel.TotalUserCount = tongUser.Count();
        //    // viewModel.TotalUsersOnlineCount = GetNumberOfUsersOnline();
        //    viewModel.TotalRolesCount = tongRole.Count();

        //    return View(viewModel);
        //}

        //Login
        public ActionResult Login()
        {
            LogOnViewModel model = new LogOnViewModel();
            return View(model);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(LogOnViewModel model, string button)
        {
            DBDataContext DBData = new DBDataContext();
            if (ModelState.IsValid)
            {
                var users = from s in DBData.Users where (s.UserName == model.UserName) select s;
                if (users.Count() != 0)
                {
                    if (users.First().Password.CompareTo(model.Password) == 0)
                    {
                        FormsAuthentication.SetAuthCookie(users.First().UserName.ToString(), true);
                        // FormsAuthentication.SetAuthCookie("3", true);

                        if (Session["Captcha"] == null || Session["Captcha"].ToString() != model.Captcha)
                        {
                            ModelState.AddModelError("Captcha", "Wrong value of sum, please try again.");

                        }
                        else
                        {
                            int roleID = ManageReportVer1.Utils.GetRoleOFUser(User.Identity.Name);
                            if(roleID==1)
                            return RedirectToAction("ViewData", "Data");
                            else
                                return RedirectToAction("ViewDepartment", "Department");

                        }
                    }
                }
                else
                {
                    //password hoac user sai
                    ModelState.AddModelError("", "Tên đăng nhập hoặc tài khoản không đúng, xin vui lòng nhập lại.");
                }
                //
            }
            // return View("LoginView", model);
            return View("Login", model);
        }

        //logout
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Home");
        }

        //captcha
        [HttpPost]
        public ActionResult Index(LogOnViewModel model)
        {
            //validate captcha
            if (Session["Captcha"] == null || Session["Captcha"].ToString() != model.Captcha)
            {
                ModelState.AddModelError("Captcha", "Wrong value of sum, please try again.");
                return View(model);
            }

            ModelState.AddModelError("", "Captcha matched.");
            return View();
        }

        public ActionResult CaptchaImage(string prefix, bool noisy = true)
        {
            var rand = new Random((int)DateTime.Now.Ticks);

            //generate new question
            int a = rand.Next(10, 99);
            int b = rand.Next(0, 9);
            var captcha = string.Format("{0} + {1} = ?", a, b);

            //store answer
            Session["Captcha" + prefix] = a + b;

            //image stream
            FileContentResult img = null;

            using (var mem = new MemoryStream())
            using (var bmp = new Bitmap(130, 30))
            using (var gfx = Graphics.FromImage((Image)bmp))
            {
                gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                //add noise
                if (noisy)
                {
                    int i, r, x, y;
                    var pen = new Pen(Color.Yellow);
                    for (i = 1; i < 10; i++)
                    {
                        pen.Color = Color.FromArgb(
                        (rand.Next(0, 255)),
                        (rand.Next(0, 255)),
                        (rand.Next(0, 255)));

                        r = rand.Next(0, (130 / 3));
                        x = rand.Next(0, 130);
                        y = rand.Next(0, 30);

                        gfx.DrawEllipse(pen, x - r, y - r, r, r);
                    }
                }

                //add question
                gfx.DrawString(captcha, new Font("Tahoma", 15), Brushes.Gray, 2, 3);

                //render as Jpeg
                bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg);
                img = this.File(mem.GetBuffer(), "image/Jpeg");
            }

            return img;
        }

    }
}
